package com.xy.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HttpSender {
	private static ExecutorService pool = Executors.newFixedThreadPool(100);
	private static HttpSender m = new HttpSender();
	private static String queryUrl = Configure.getProperty("backURL")
			+ "/query";
	private static String notifyUrl = Configure.getProperty("frontURL")
			+ "/notify";

	public static void query(Number rid) {
		send(queryUrl, rid);
	}

	public static void notify(Number rid) {
		send(notifyUrl, rid);
	}

	public static void send(String u, Number rid) {
		pool.execute(new Thread(m.new SendThread(u, rid)));

	}

	class SendThread implements Runnable {
		String url;
		Number rid;

		public SendThread(String u, Number rid) {
			url = u;
			this.rid = rid;
		}

		public void run() {

			try {
				Thread.sleep(1000);
				String data = URLEncoder.encode("rid=" + rid, "UTF-8");
				URL url = new URL(this.url + "?rid=" + rid);
				URLConnection conn = url.openConnection();
				conn.setDoOutput(true);
				conn.setRequestProperty("User-Agent", "MSIE");
				conn.connect();
				/*
				 * OutputStreamWriter wr = new OutputStreamWriter(
				 * conn.getOutputStream()); wr.write(data); wr.flush();
				 */
				BufferedReader rd = new BufferedReader(new InputStreamReader(
						conn.getInputStream()));
				String line;
				StringBuffer sb = new StringBuffer();
				while ((line = rd.readLine()) != null) {
					sb.append(line);
				}
				// wr.close();
				rd.close();
				// return sb.toString();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// return "error";

		}
	}

	// public static void main(String args[]) { notify(19); query(19); }

}
